<?php

namespace App\Service;

class BaiduSMS
{
    //终端，默认为sms.bj.baidubce.com
    protected static $endPoint;
    //AK
    protected static $accessKey;
    //SK
    protected static $secretAccessKey;

    function __construct(array $config)
    {
        // 配置信息
        $default = [
            'endPoint'        => 'smsv3.bj.baidubce.com',
            'accessKey'       => 'ALTAKdUwyVdZbGim9i7WX6W5DE',
            'secretAccessKey' => 'bd3d5f3dcbd7492f8e308e053e0be1a9',
        ];
        $config  = array_merge($default, $config);

        self::$endPoint        = $config['endPoint'] ?? 'smsv3.bj.baidubce.com';
        self::$accessKey       = $config['accessKey'] ?? '**********42d69bb01f************';
        self::$secretAccessKey = $config['secretAccessKey'] ?? '****537ca049949f********';

    }

    /**
     * TODO 除了发送短信以外，其他的都是百度签名里面的方法
     * $message = array(
     *     "signatureId" => "2ZWOI6xV-AgpZ-2zIz",          //你申请的签名ID
     *     "mobile" => "18852983890",  //手机电话号码
     *     "template" => "smsTpl:e7476122a1c24e37b3b0de19d04ae901",  //模板的唯一标识
     *     "contentVar" => array(
     *       "code" =>  "283789",  //模板里面的key变量  ${key}
     *     ),
     *   );
     *
     *   返回一个数组:
     *   成功：array( 'code' => '1000', 'message' => '成功', 'requestId' => '45e1235-3b07-4421-83f8-cf4c74b1232c', )
     *   失败：array( 'requestId' => 'a1145bba-95c0-4341-83de-115d41741f0f', 'code' => '401', 'message' => '权限认证失败', )
     */
    public function sendSms($message_array)
    {
        //生成json格式
        $json_data = json_encode($message_array);

        //生成签名
        $endPoint = self::$endPoint;
        $path     = '/api/v3/sendSms';
        $headers  = $this->header($endPoint, $path, $json_data);
        $url      = 'http://'.$endPoint.$path;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $json_data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);

        return json_decode($result, true);
    }

    // 生成签名
    public function header($endPoint, $path, $json_data)
    {
        // 参数
        $credentials = ["ak" => self::$accessKey, "sk" => self::$secretAccessKey];
        $httpMethod  = "POST";
        $str_sha256  = hash('sha256', $json_data);
        $params      = [];

        // 时间
        $timestamp = new \DateTime();
        $timestamp->setTimezone(new \DateTimeZone("GMT"));
        $datetime     = $timestamp->format("Y-m-d\TH:i:s\Z");
        $datetime_gmt = $timestamp->format("D, d M Y H:i:s T");


        // 用于签名的header
        $headers = [
            "Host"                 => $endPoint,
            'x-bce-content-sha256' => $str_sha256,
            'Content-Length'       => strlen($json_data),
            'Content-Type'         => "application/json",
            'x-bce-date'           => $datetime,
        ];
        $options = ['timestamp' => $timestamp, 'headersToSign' => array('host', 'x-bce-content-sha256',),];
        $ret     = (new BaiduSign())->sign($credentials, $httpMethod, $path, $headers, $params, $options);

        // 发送短信的header
        $headers_curl = [
            'Content-Type:application/json',
            'Host:'.$endPoint,
            'x-bce-date:'.$datetime,
            'Content-Length:'.strlen($json_data),
            'x-bce-content-sha256:'.$str_sha256,
            'Authorization:'.$ret,
            "Accept-Encoding: gzip,deflate",
            'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/2008052906 Firefox/3.0',
            'Date:'.$datetime_gmt,
        ];

        return $headers_curl;
    }
}





